import {Component} from "@angular/core";
import {NavController, ToastController, ModalController, LoadingController} from "ionic-angular";
import {Shipin} from "../../pages/homes/shipin";
import {SearchService} from "../../services/search.service";


@Component({
  templateUrl: 'home.html',
  providers: [SearchService],
})
export class HomePage {
  public movieHome={};
  public movieHomeSub = {
    "movie" :[],
    "teleplay" : []
  }

  constructor(public loadingCtrl: LoadingController, public navCtrl: NavController, public toastCtrl: ToastController, public modalCtrl: ModalController, public searchService: SearchService) {

  }

  ionViewDidLoad() {
    // 当天内不重复执行获取首页请求
    let date = new Date();
    if (!localStorage['movieHome'] || localStorage['movieHomeDate'] != date.getDay()) {
      this.getMovieHome();
    } else {
      this.movieHome = JSON.parse(localStorage['movieHome']);
      this.movieHomeSub = {
        "movie": [],
        "teleplay": []
      };
      for (let i = 0; i < this.movieHome['movie'].length; i++) {
        if (i <= 5) {
          this.movieHomeSub['movie'].push(this.movieHome['movie'][i])
        }
      }
      for (let i = 0; i < this.movieHome['teleplay'].length; i++) {
        if (i <= 5) {
          this.movieHomeSub['teleplay'].push(this.movieHome['teleplay'][i])
        }
      }
    }
  }

  getMovieHome() {
    this.searchService.getMovieHome().subscribe(
      data => {
        this.movieHome = data;
        if (data) {
          this.movieHomeSub = {
            "movie": [],
            "teleplay": []
          };
          for (let i = 0; i < data['movie'].length; i++) {
            if (i <= 5) {
              this.movieHomeSub['movie'].push(data['movie'][i])
            }
          }
          for (let i = 0; i < data['teleplay'].length; i++) {
            if (i <= 5) {
              this.movieHomeSub['teleplay'].push(data['teleplay'][i])
            }
          }
        }
        let date = new Date();
        localStorage['movieHomeDate'] = date.getDay();
        localStorage['movieHome'] = JSON.stringify(data);
      },
      error => {
        this.showToast(error._body);
      }
    );
  }


	onshipin(){
      this.navCtrl.push(Shipin)
	}

	// getMovieHome(){
	//   this.showLoading();
	//   this.hideLoading();
  // }

  public loading= null;
  showLoading(){
    this.loading = this.loadingCtrl.create({
      spinner: 'hide',
      content:`<div class="qn-ba"><img src="assets/images/lo.gif" /></div>`,
      showBackdrop:true,
      // duration: 20000,
    });
    this.loading.present();
  }

  hideLoading(){
    if (this.loading != null){
      this.loading.dismissAll();
    }
  }

  showToast(message:string){
    let toast= this.toastCtrl.create({
      message:message,
      duration:3000,
      position:'top'
    });
    toast.present();
  }
}
